package com.bocai.dahuatech.ui.frag;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.OrderListBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseFragment;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.ui.adapter.MyOrderAdapterHolder;
import com.bocai.dahuatech.ui.pressent.MyorderPressent;
import com.bocai.dahuatech.ui.view.LoadMoreRecyclerView;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 我的订单列表界面
 */
@SuppressLint("ValidFragment")
public class FragmentMyOrder extends BaseFragment implements View.OnClickListener,MyorderPressent{
    private View view;
    private String mQuery;
    @Bind(R.id.lv_search_order)
    LoadMoreRecyclerView lvSearchOrder;
    @Bind(R.id.swipe_order)
    SwipeRefreshLayout swipeOrder;
    OrderListBean orderListBean;
    MyOrderAdapterHolder adapter;
    int page=1;
    boolean isshow=false;
    String adptermQuery;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.myorder_fragment, container, false);
        initView(view);
        return view;
    }
    public FragmentMyOrder(String query)
    {
        this.mQuery = query;
    }


    /** Fragment当前状态是否可见 */
    protected boolean isVisible;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint())
        {
            if(!isVisible)
            {
                getData();
                isVisible = true;
            }
        }
    }

    private void initView(View view)
    {
        ButterKnife.bind(this, view);
        lvSearchOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        initEvent();
    }
    Observer<BaseBean> observer=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            swipeOrder.setRefreshing(false);
            Log.e("error", "zhang");
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            swipeOrder.setRefreshing(false);
            if (baseBean.getReturnNo().equals("1"))
            {
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                orderListBean=new Gson().fromJson(result,OrderListBean.class);
                setDatas();
            }
        }
    };

    private void setDatas()
    {
        if(page==1)
        {
            adapter=new MyOrderAdapterHolder(getActivity(),orderListBean.getContent(),this,mQuery);
            lvSearchOrder.setAdapter(adapter);
        }else
        {
            adapter.addDatas(orderListBean.getContent());
        }
        if(orderListBean.getContent().size()==0)
        {
            lvSearchOrder.notifyMoreFinish(false);
        }else
        {
            lvSearchOrder.notifyMoreFinish(true);
        }
    }


    @Override
    public void onEventMainThread(MainEvent event) {
        super.onEventMainThread(event);
        adptermQuery=event.mQuery;
        switch (event.msg){
            case "ordercanel":
                //取消订单
                showLoading();
                getTestApi().orderCancel(SharePrefencesUtil.getFID(getActivity()),event.orderId,2,SharePrefencesUtil.getCustomerCode(getActivity()))
                        .compose(this.<BaseBean>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseBean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading();
                                if (mQuery.equals(adptermQuery)){
                                    showToast(R.string.neterror);
                                }
                            }
                            @Override
                            public void onNext(BaseBean baseBean) {
                                hideLoading();
                                page=1;
                                getData();
                                if (mQuery.equals(adptermQuery)){
                                    showToast(baseBean.getReturnInfo());
                                }
                            }
                        });
//                showLoading();
//                getTestApi().deleteOrder(event.orderId,SharePrefencesUtil.getFID(getActivity()),SharePrefencesUtil.getCustomerCode(getActivity()))
//                        .compose(this.<BaseBean>bindToLifecycle())
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Observer<BaseBean>() {
//                            @Override
//                            public void onCompleted() {
//
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                hideLoading();
//                                showToast("网络错误");
//                            }
//
//                            @Override
//                            public void onNext(BaseBean baseBean) {
//                                hideLoading();
////                                showToast(baseBean.getReturnInfo());
//                                page=1;
//                                getData();
//                            }
//                        });
                break;
            case "receivegoods":
                //确认收货
                showLoading();
                getTestApi().receiveGoods(event.orderId,SharePrefencesUtil.getFID(getActivity()),SharePrefencesUtil.getCustomerCode(getActivity()))
                        .compose(this.<BaseBean>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseBean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading();
                                showToast(R.string.neterror);
                            }

                            @Override
                            public void onNext(BaseBean baseBean) {
                                hideLoading();
                                showToast(baseBean.getReturnInfo());
                            }
                        });

                break;
            case "orderset":
                //返回购物车修改
                showLoading();
                getTestApi().orderCancel(SharePrefencesUtil.getFID(getActivity()),event.orderId,1,SharePrefencesUtil.getCustomerCode(getActivity()))
                        .compose(this.<BaseBean>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseBean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading();
                                if (mQuery.equals(adptermQuery)){

                                    showToast(R.string.neterror);
                                }
//                                EventBus.getDefault().post(new MainEvent("goshopcart"));
//                                getActivity().finish();
                            }

                            @Override
                            public void onNext(BaseBean baseBean) {
                                hideLoading();
                                if (mQuery.equals(adptermQuery)){
                                    showToast(baseBean.getReturnInfo());
                                    EventBus.getDefault().post(new MainEvent("goshopcart"));
                                }
                                getActivity().finish();
                            }
                        });
                break;
//            case "deleteorder":
//                showLoading();
//                getTestApi().deleteOrder(event.orderId,SharePrefencesUtil.getFID(getActivity()),SharePrefencesUtil.getCustomerCode(getActivity()))
//                        .compose(this.<BaseBean>bindToLifecycle())
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Observer<BaseBean>() {
//                            @Override
//                            public void onCompleted() {
//
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                hideLoading();
//                                showToast("网络错误");
//                            }
//
//                            @Override
//                            public void onNext(BaseBean baseBean) {
//                                hideLoading();
//                                showToast(baseBean.getReturnInfo());
//                            }
//                        });
//                break;
        }
    }

    private void getData() {
        showLoading();
        getTestApi().getOrderList(SharePrefencesUtil.getCustomerCode(getActivity()),"","",mQuery,page)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void initEvent() {
        lvSearchOrder.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getData();
            }
        });
        swipeOrder.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page=1;
                getData();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    @Override
    public void onResume() {

        super.onResume();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
        }
    }

    @Override
    public void setIsShow(boolean isShow) {
        this.isshow=isShow;
    }
}
